#!/usr/bin/env python3
"""
GGB Generation Conversation API 客户端示例

这个示例展示了如何使用 Python 客户端与对话 API 进行交互
"""

import httpx
import json
import asyncio
import sys

# API 配置
API_BASE_URL = "http://localhost:8080"
API_ENDPOINT = "/api/v2/chat"

async def chat_with_api(user_id: int, message: str, conversation_id: int = None, title: str = None):
    """
    与 API 进行对话
    
    Args:
        user_id: 用户ID
        message: 用户消息
        conversation_id: 对话ID（可选）
        title: 对话标题（可选）
    """
    # 构建请求数据
    request_data = {
        "user_id": user_id,
        "message": message
    }
    
    if conversation_id:
        request_data["conversation_id"] = conversation_id
    
    if title:
        request_data["title"] = title
    
    print(f"🚀 发送请求到: {API_BASE_URL}{API_ENDPOINT}")
    print(f"📝 请求数据: {json.dumps(request_data, indent=2, ensure_ascii=False)}")
    print("=" * 50)
    
    try:
        async with httpx.AsyncClient(timeout=60.0) as client:
            async with client.stream("POST", f"{API_BASE_URL}{API_ENDPOINT}", 
                                    json=request_data) as response:
                
                print(f"📊 响应状态: {response.status_code}")
                print(f"📋 响应头: {dict(response.headers)}")
                print("=" * 50)
                print("📺 流式响应:")
                print()
                
                if response.status_code != 200:
                    error_text = await response.aread()
                    print(f"❌ 错误: {error_text.decode()}")
                    return
                
                step_count = 0
                async for chunk in response.aiter_text():
                    if chunk.strip():
                        try:
                            # 移除 "data: " 前缀
                            data_str = chunk.replace("data: ", "").strip()
                            data = json.loads(data_str)
                            
                            step_count += 1
                            print(f"[步骤 {step_count}] {data['type']}: {data['content']}")
                            
                            if data['type'] == 'complete':
                                print()
                                print("✅ 处理完成!")
                                break
                            elif data['type'] == 'error':
                                print()
                                print("❌ 处理出错!")
                                break
                                
                        except json.JSONDecodeError:
                            print(f"📄 原始数据: {chunk}")
                
    except httpx.ConnectError:
        print("❌ 连接错误: 无法连接到服务器")
        print("💡 请确保服务已启动: ./introduction_files/start_conversation_service.sh")
    except Exception as e:
        print(f"❌ 错误: {str(e)}")

async def main():
    """主函数"""
    print("🎯 GGB Generation Conversation API 客户端示例")
    print("=" * 50)
    
    # 示例1: 创建新对话
    print("📝 示例1: 创建新对话")
    await chat_with_api(
        user_id=1,
        message="在平面直角坐标系中，已知点A(0,0)，点B(4,0)，点C(0,3)。求三角形ABC的面积。",
        title="几何问题求解"
    )
    
    print("\n" + "=" * 50)
    
    # 示例2: 在现有对话中发送消息
    print("📝 示例2: 在现有对话中发送消息")
    await chat_with_api(
        user_id=1,
        conversation_id=1,
        message="请详细解释计算过程"
    )

if __name__ == "__main__":
    # 检查服务是否运行
    try:
        import requests
        response = requests.get(f"{API_BASE_URL}/health", timeout=5)
        if response.status_code != 200:
            print("⚠️  警告: 服务可能未正常运行")
    except:
        print("⚠️  警告: 无法连接到服务，请确保服务已启动")
        print("💡 启动命令: ./introduction_files/start_conversation_service.sh")
        print()
    
    # 运行示例
    asyncio.run(main()) 